import { Injectable } from '@nestjs/common';
import axios, { AxiosRequestConfig } from 'axios';
@Injectable()
export class AxiosService {
  async request(config: AxiosRequestConfig) {
    return axios(config);
  }
  async get(url: string, config?: AxiosRequestConfig) {
    return axios.get(url, config);
  }
  async post(url: string, data?: any, config?: AxiosRequestConfig) {
    return axios.post(url, data, config);
  }
  async put(url: string, data?: any, config?: AxiosRequestConfig) {
    return axios.put(url, data, config);
  }
  async delete(url: string, config?: AxiosRequestConfig) {
    return axios.delete(url, config);
  }
  async retryWithRequest(
    requestCallback: () => Promise<any>,
    retryCount: number = 5,
    delay: number = 2000,
  ) {
    let retry = 0;
    while (retry < retryCount) {
      try {
        return await requestCallback();
      } catch (error) {
        console.log(`Retrying request (${retry + 1}/${retryCount})...${error.message}`);
        retry++;
        if (retry >= retryCount) {
          console.log('请求失败', error);
          throw error;
        }
        await new Promise((resolve) => setTimeout(resolve, delay));
        return this.retryWithRequest(requestCallback, retryCount, delay);
      }
    }
  }
}
